package im.jsmith.android.bloxbreaker;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.pool.GenericPool;

import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;

/**
 * @author Jordon Smith
 */
public class BlockPool extends GenericPool<Block> {
	private Engine mEngine;
	private PhysicsWorld mPhysicsWorld;
	private TextureRegion mTexReg;
	private FixtureDef mFixtureDef;
	
	public BlockPool(Engine pEngine, PhysicsWorld pPhysicsWorld, TextureRegion pTexReg) {
		mEngine = pEngine;
		mPhysicsWorld = pPhysicsWorld;
		mTexReg = pTexReg;
		mFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 0);
	}

	@Override
	protected Block onAllocatePoolItem() {
		Block block = new Block();
		block.setSprite(new Sprite(0, 0, mTexReg));
		block.setBody(PhysicsFactory.createBoxBody(mPhysicsWorld, block.getSprite(), BodyType.StaticBody, mFixtureDef));
		return block;
	}
	
	@Override
	protected void onHandleObtainItem(Block block) {	
		block.getSprite().reset();
		mEngine.getScene().getBottomLayer().addEntity(block.getSprite());
		mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(block.getSprite(), block.getBody(), true, false, false, false));
		block.getBody().setUserData(block);
		block.getBody().setActive(true);
	}

	@Override
	protected void onHandleRecycleItem(final Block block) {
		mEngine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				PhysicsConnector connector = mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(block.getSprite());
				mPhysicsWorld.unregisterPhysicsConnector(connector);
				mEngine.getScene().getBottomLayer().removeEntity(block.getSprite());
				block.getBody().setActive(false);
			}
		});
	}
}
